import TileLayer from 'ol/layer/Tile';
import Map from 'ol/Map';
import XYZ from 'ol/source/XYZ';
import View from 'ol/View';
import { useLayoutEffect, useState } from 'react';

type MapType = [
    map:null | Map,
    isLoaded:boolean,
];

export default function useMap(mapDiv:string):MapType {
  const [mapState, setMapState] = useState<MapType>([null, false]);
  console.log('useMap');

  useLayoutEffect(() => {
    setTimeout(() => {
      const map = new Map({
        target: mapDiv,
        layers: [
          new TileLayer({
            source: new XYZ({
              url: 'https://services.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer/'
                                + 'tile/{z}/{y}/{x}',
              maxZoom: 10,
            }),
          }),
        ],
        view: new View({
          center: [11995526.369499953, 3898624.6089715846],
          zoom: 4,
        }),
      });
      setMapState([map, true]);
    }, 0);

    return () => { };
  }, [mapDiv]);

  // return tuplify(olMap, isLoaded);
  return mapState;
}
